package com.client.task;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

import com.client.act.CollectionGridAct;
import com.client.act.R;
import com.client.bean.BirdList;
import com.client.bean.BirdMessage;
import com.client.bean.User;
import com.client.common.ToastUtil;
import com.client.common.ValueStack;
import com.client.db.DataService;
import com.client.net.Request;
import com.clinet.cache.Log;

//读取数据。有就发广播用户点击即可查看
public class TimeSynchroziedRunnable implements Runnable {

	private DataService mDataService = null;
	private Request mRequest = null;

	private final Context context;
	// 最新数据
	private String path = ValueStack.ROOT
			+ "/forestry/birdMessage_getAll.action";

	private BirdList mBirdList = null;

	// &&sync=true加这个是全部数据，不加是最新数据

	public TimeSynchroziedRunnable(Context context) {
		this.context = context;
		mRequest = new Request(path);
		if (mDataService == null) {
			mDataService = new DataService(context);
		}
	}

	// 正确返回：
	// {"items":[{"birdId":"40289381368be15b01368c0804e20002",
	// "birdImage":"753726d6cdc444cd96ef4d0fd1c18d73.jpg","birdName":"fdasg",
	// "collectLoaction":"","date":"","deadDes":"fdsgfdsg",
	// "deadImage":"381ba853e1dc4114a3b9e19cf3ac7891.jpg","deadNum":0,"direct":"","distance":"","healthNum":0,
	// "kind":"23","latitude":"","longitude":"","num":232,"place":"","sickDes":"43",
	// "sickImage":"81c7484b13664748b5fad4fa60c6b23e.jpg","sickNum":0,"status":"","stayPlace":""}],
	// "message":"OK","success":true,"totalNum":1}
	// 错误返回：
	// {"success":false,"message":"请输入用户名或密码!"}//没用登录的情况

	@Override
	public void run() {
		while(true)
		{
			Log.i("TimeSynchroziedRunnable.run ------------------------- ");
			try {
				Thread.sleep(1000*60);
			} catch (InterruptedException e) {
			}
			{
				getNewDate();
			}
		}
		
	}
	public void getNewDate()
	{
		User muser = (User) ValueStack.getInstance().getSessionValue("USER");
		Map<String, String> ps = new HashMap<String, String>();
		ps.put("username", muser.userName);
		ps.put("password", muser.password);
		//
		path = path + ";jsessionid" + muser.sessionid;
		try {
			String temp = mRequest.postFormData(ps);
			Log.i("TimeSynchroziedRunnable.run postText" + temp);
			JSONObject obj = new JSONObject(temp);
			int totalNum = obj.getInt("totalNum");
			if (totalNum > 0) {
				Log.i("最新数据-------------------");
				if(mBirdList!=null)
				{
					mBirdList.clear();
					mBirdList=null;
				}
				mBirdList = new BirdList();
				JSONArray items = obj.getJSONArray("items");
				BirdMessage mBirdMessage = null;
				for (int i = 0; i < items.length(); i++) {
					JSONObject o = items.getJSONObject(i);
					mBirdMessage = new BirdMessage();
					mBirdMessage.birdId = o.getString("birdId");
					mBirdMessage.birdImage = ValueStack.IMAGEROOT
							+ o.getString("birdImage");
					mBirdMessage.birdName = o.getString("birdName");
					mBirdMessage.collectLoaction = o
							.getString("collectLoaction");
					mBirdMessage.date = o.getString("date");
					mBirdMessage.deadDes = o.getString("deadDes");
					mBirdMessage.deadImage = ValueStack.IMAGEROOT
							+ o.getString("deadImage");
					mBirdMessage.deadNum = o.getString("deadNum");
					mBirdMessage.direct = o.getString("direct");
					mBirdMessage.distance = o.getString("distance");
					mBirdMessage.healthNum = o.getString("healthNum");
					mBirdMessage.kind = o.getString("kind");
					mBirdMessage.latitude = o.getString("latitude");
					mBirdMessage.longitude = o.getString("longitude");
					mBirdMessage.num = o.getString("num");
					mBirdMessage.place = o.getString("place");
					mBirdMessage.sickDes = o.getString("sickDes");
					mBirdMessage.sickImage = ValueStack.IMAGEROOT
							+ o.getString("sickImage");
					mBirdMessage.sickNum = o.getString("sickNum");
					mBirdMessage.status = o.getString("status");
					mBirdMessage.stayPlace = o.getString("stayPlace");
					mBirdMessage.pinyin = o
					.getString("birdNamePinyin");
					mBirdMessage.uploaded="true";
					mBirdList.addBirdMessage(mBirdMessage);
				}
				mDataService.saveBirdMessage(mBirdList);
				// 发送广播
//				showNotification(context, totalNum);
				ToastUtil.toast(context, "接收到最新数据:" + totalNum + "条");
			}

		} catch (Exception e) {
			Log.i("Exception" + e.getMessage());
		}
	}

	private void showNotification(Context context, Integer totalNum) {
		Log.i("--------------TimeSynchroziedRunnable.run-----------showNotification-"+totalNum);
		NotificationManager mNotificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		long when = System.currentTimeMillis();
		Intent notificationIntent = new Intent(context, CollectionGridAct.class);
		PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
				notificationIntent, 0);
		Notification notification = new Notification(R.drawable.icon,
				"接收到最新数据:" + totalNum + "条", when);
		notification.defaults = Notification.DEFAULT_VIBRATE;
		notification.setLatestEventInfo(context, "最新数据", "接收到最新数据:" + totalNum
				+ "条", contentIntent);
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		mNotificationManager.notify(0, notification);
	}
}
